/* eslint-disable no-unused-vars */
import React, { Component, memo } from 'react';
import {
  Card,
  Form,
  Button,
  Input,
  Table,
  Space,
  Modal,
  message,
  Upload,
} from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  FileAddOutlined,
  DownloadOutlined,
  UploadOutlined,
  EditOutlined,
  RedoOutlined,
} from '@ant-design/icons';
import styles from './style.module.less';
import { connect } from 'react-redux';
import Highlighter from 'react-highlight-words';

const itemStyle = {
  margin: ' 0 0.5rem 0.6rem',
};

const formLayout = {
  labelCol: { xs: 4, sn: 4 },
  wrapperCol: { xs: 24, sm: 20 },
};

// const grade = ['2016', '2017', '2018', '2019']

const modalTitle = ['', '新增', '编辑'];

const CollectionCreateForm = memo(
  ({ visible, onCreate, onCancel, type, record }) => {
    //子组件   展开弹窗
    const [form] = Form.useForm();
    form.setFieldsValue(record);

    const onOK = () => {
      form
        .validateFields()
        .then((values) => {
          form.resetFields();
          onCreate(values, record.stuId);
        })
        .catch((info) => {});
    };
    return (
      <Modal
        title={modalTitle[type]}
        onCancel={onCancel}
        onOk={onCreate}
        visible={visible}
        onOk={onOK}
      >
        <Form
          {...formLayout}
          // initialValues={records} 默认值，动态值用setFieldsValue
          form={form}
        >
          <Form.Item
            name="stuNo"
            label="学号"
            rules={[{ required: true, message: '请输入学生学号' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入学生姓名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号码"
            rules={[{ required: true, message: '请输入学生联系方式' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="电子邮箱"
            rules={[{ required: true, message: '请输入学生学号' }]}
          >
            <Input />
          </Form.Item>
          {/* <Form.Item name='grade' label='年级' rules={[
            {required: true, message: '请输入选择年级'}
          ]}>
            <Select>
              {
                grade.map( item => <Select.Option key={item} value={item}>{item}级</Select.Option>)
              }
            </Select>
          </Form.Item> */}
        </Form>
      </Modal>
    );
  },
);

class ManagementStudent extends Component {
  state = {
    selectedRowKeys: [],
    visible: false,
    type: 1, // 1为新增 2为删除
    record: {
      id: '',
      name: '',
      tel: '',
      email: '',
    },
  };
  searchText = {
    name: '',
    stuNo: '',
  };

  componentDidMount() {
    const { fetch } = this.props;
    localStorage.getItem('grade')
      ? fetch({ gradeId: localStorage.getItem('grade') })
      : message.error('年级设置错误');
  }

  deleteOne = (record) => {
    const { deleteStudent } = this.props;

    deleteStudent([record.id]);
  };

  deleteRow = () => {
    const { deleteStudent } = this.props;
    const { selectedRowKeys } = this.state;
    deleteStudent(selectedRowKeys);
    this.setState({
      selectedRowKeys: [],
    });
  };

  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        selectedRowKeys: selectedRowKeys,
      });
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  onCreate = (values, stuId) => {
    const { add, update } = this.props;
    const { type } = this.state;
    this.hiddenModal();
    if (type == 1) {
      add({ ...values, grade: '2018' });
    } else {
      update({ ...values, stuId: stuId });
    }
    // this.setState({
    //   visible: false
    // })
    // add(values)
  };

  hiddenModal = () => {
    this.setState({
      visible: false,
    });
  };

  add = () => {
    this.setState({
      visible: true,
      type: 1,
      record: { stuNo: '', name: '', phone: '', email: '', grade: '' },
    });
  };

  edit = (record) => {
    this.setState({
      visible: true,
      type: 2,
      record: record,
    });
  };

  search = () => {
    this.setState({});
  };
  render() {
    const { visible, type, record, selectedRowKeys } = this.state;
    const store = this.props.store;
    const columns = [
      {
        title: '学号',
        dataIndex: 'stuNo',
        key: 'stuNo',
        filteredValue: [this.searchText.stuNo],
        onFilter: (value, record) => record.stuNo.toString().includes(value),
        render: (text) => {
          return (
            <Highlighter
              highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
              searchWords={[this.searchText.stuNo]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          );
        },
      },
      {
        title: '姓名',
        dataIndex: 'stuName',
        key: 'stuName',
        filteredValue: [this.searchText.name],
        // onFilter: (value, record) =>
        //             record.stuName
        //               .toString()
        //               .includes(value),
        render: (text) => {
          return (
            <Highlighter
              highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
              searchWords={[this.searchText.name]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          );
        },
      },
      {
        title: '手机号',
        dataIndex: 'phoneNumber',
        key: 'phoneNumber',
      },
      {
        title: '电子邮箱',
        dataIndex: 'stuEmaill',
        key: 'stuEmail',
      },
      // {
      //   title: '年级',
      //   dataIndex: 'grade',
      //   key: 'grade'
      // },
      {
        title: '操作',
        render: (record) => {
          //
          return (
            <Space size="middle">
              <a onClick={() => this.edit(record)}>
                <EditOutlined /> 编辑
              </a>
              <a
                onClick={() => {
                  this.deleteOne(record);
                }}
                className="ant-dropdown-link"
              >
                <DeleteOutlined /> 删除
              </a>
              {/* <a className="ant-dropdown-link">
              <RedoOutlined />重置 
            </a> */}
            </Space>
          );
        },
      },
    ];
    return (
      <Card
        title={
          <div className={styles.tableOptions}>
            <div style={itemStyle} className={`${styles.inputItem}`}>
              <span>学号</span>
              <Input
                onChange={(e) => (this.searchText.stuNo = e.target.value)}
              />
            </div>
            <div style={itemStyle} className={`${styles.inputItem}`}>
              <span>姓名</span>
              <Input
                onChange={(e) => (this.searchText.name = e.target.value)}
              />
            </div>
            <Button
              className={styles.normal}
              disabled={store.loading}
              icon={<SearchOutlined />}
              type="primary"
              style={itemStyle}
              onClick={this.search}
            >
              搜索
            </Button>

            <Button
              className={styles.normal}
              disabled={store.loading}
              icon={<DeleteOutlined />}
              type="primary"
              style={itemStyle}
              onClick={() => {
                this.searchText.name = '';
                this.searchText.stuNo = '';
                this.search();
              }}
            >
              清空搜索
            </Button>
            <Button
              className={styles.add}
              disabled={store.loading}
              icon={<FileAddOutlined />}
              type="primary"
              onClick={this.add}
              style={itemStyle}
            >
              新增
            </Button>
            <Upload
              beforeUpload={(file) => {
                this.props.uploadFile({
                  file: file,
                });
                return false;
              }}
              itemRender={() => null}
              disabled={store.loading}
            >
              <Button
                className={styles.normal}
                disabled={store.loading}
                type="primary"
                icon={<UploadOutlined />}
                style={itemStyle}
              >
                上传模板
              </Button>
            </Upload>
            <Button icon={<DownloadOutlined />} style={itemStyle}>
              下载模板
            </Button>
          </div>
        }
      >
        {/* <Test list = {store.list}/> */}
        <Table
          rowSelection={{
            selectedRowKeys: selectedRowKeys,
            ...this.rowSelection,
          }}
          dataSource={store.studentList}
          columns={columns}
          loading={store.loading}
          rowKey="stuId"
        />

        <CollectionCreateForm
          record={record}
          type={type}
          visible={visible}
          onCreate={this.onCreate}
          onCancel={this.hiddenModal}
        />
      </Card>
    );
  }
}

const mapStateToProps = ({ managementStudent }) => ({
  store: managementStudent,
});

const mapDispatchToProps = (dispatch) => ({
  add: dispatch.managementStudent.add,
  update: dispatch.managementStudent.update,
  deleteStudent: dispatch.managementStudent.delete,
  fetch: dispatch.managementStudent.fetch,
  uploadFile: dispatch.managementStudent.uploadFile,
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(memo(ManagementStudent));
